package com.pmdb.util;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import com.pmdb.core.data.Country;

public class CountryUtil {

   private static final Logger LOG = Logger.getLogger(CountryUtil.class);
   
   private static final int NUM_ITEMS = 7;

   private static final String[] countries = new String[] {
      "Korea",
      "Japan",
      "China",
      "Hong Kong",
      "USA",
      "France",
      "Germany"};

   private static int countryIdx = -1;
   private static List<Country> items = new ArrayList<Country>();
   private EntityManager em = null;

   public CountryUtil(EntityManager em) {
      this.em = em;
   }

   public void generateCountries() {
     for (int i = 0; i < NUM_ITEMS; ++i) {
       items.add(createCountry());
     }
   }

   public Country getCountry(int index) {
     if (index >= items.size()) {
       return null;
     }
     return items.get(index);
   }

   public int getCountryCount() {
     return items.size();
   }

   private Country createCountry() {
     countryIdx++;
     return new Country(countries[countryIdx]);
   }

   private Country createCountry(String name) {
     Country newCountry = new Country(name);
     em.persist(newCountry);
     return newCountry;
   }

   public Country findCountryByName(String name) {
      Query countryByName = em.createQuery("from Country c where c.name like :name");
      countryByName.setParameter("name", name);
      
      if(countryByName.getResultList().size() == 0) {
         LOG.debug("Not Found: " + name);
         return null;
      }
      else {
         LOG.debug("Found: " + name);
         return (Country)countryByName.getSingleResult();
      }
   }

   public Country findOrCreate(String name) {
      Country country = this.findCountryByName(name);
      if(country == null) {
         country = this.createCountry(name);
         LOG.debug("Country: " + name + " not found! (created)");
      }
      return country;
   }
}
